package com.ethereal.petmanagement.controller;

import com.ethereal.petmanagement.dto.UserDTO;
import com.ethereal.petmanagement.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@WebServlet(urlPatterns = {"*.do"})
public class UserController extends HttpServlet {
    static UserServiceImpl userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的URI地址信息
        String uri = req.getRequestURI();
        System.out.println(uri);
        //截取其中的方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
        System.out.println(methodName);

        try {
            //使用反射机制获取在本类中声明了的方法
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 允许访问private方法
            method.setAccessible(true);
            // 执行方法
            method.invoke(this, req, resp);
        } catch (Exception e) {
            throw new RuntimeException("调用方法出错！");
        }

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp){
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(req.getParameter("username"));
        userDTO.setPassword(req.getParameter("password"));
        userService.login(userDTO);
    }

    private void register(HttpServletRequest req, HttpServletResponse resp){
        PrintWriter pw = null;
        try {
            pw = resp.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(req.getParameter("username"));
        userDTO.setPassword(req.getParameter("password"));
        userDTO.setPassword(req.getParameter("phone"));
        if (userService.register(userDTO)){
            pw.write("Register Success!");
            req.getRequestDispatcher("/login");
        }else {
            pw.write("Register Error!");
        }
    }
}
